import os
import logging
import sys
from logging.handlers import TimedRotatingFileHandler, RotatingFileHandler
from config.Config import Config


def setup_logger(object_name="my_logger", file_name="Operation.log"):
    """
    设置并返回一个按天轮替的日志记录器。
    """
    # 创建logger对象
    logger = logging.getLogger(object_name)
    
    # 避免重复添加handler
    if logger.handlers:
        return logger
    
    # 从配置获取日志级别
    log_level = getattr(logging, Config.LOG_LEVEL.upper(), logging.INFO)
    logger.setLevel(log_level)
    
    # 创建日志目录
    file_path = os.path.join(os.getcwd(), "Logs")
    if not os.path.exists(file_path):
        os.mkdir(file_path)
    
    logfile = os.path.join(file_path, file_name)
    
    # 创建TimedRotatingFileHandler实例
    file_handler = TimedRotatingFileHandler(
        filename=logfile,
        when='midnight',
        interval=1,
        backupCount=30,
        encoding='utf-8'
    )
    file_handler.suffix = "%Y%m%d"
    
    # 创建控制台handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(log_level)
    
    # 定义日志输出格式
    formatter = logging.Formatter(
        fmt="%(asctime)s - %(name)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    # 添加handlers
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger


def get_logger(name=None):
    """
    获取logger实例的便捷方法
    """
    return setup_logger(name or "app_logger")


# 创建默认logger
logger = get_logger()
